在Lodash / Javascript中展平和替换对象字段

时间:2017-01-04 10:04:00

标签: javascript json lodash

我有以下数据,其中包含嵌套字段。 我目前正在使用For循环来替换嵌套字段,但它似乎非常古老。

我想将嵌套字段展平为名称的键:

[{
        "id": 1,
        "name": Sally,
        "country": {
            "id": 1,
            "name": "Chile"
        },
        "city": {
            "id": 1,
            "name": "Santiago"
        },
        "city-spot": {
            "id": 1,
            "name": "Downtown",
        },
    },

    {
        "id": 2,
        "name": Tom,
        "country": {
            "id": 3,
            "name": "Canada"
        },
        "city": {
            "id": 2,
            "name": "Vancouver"
        },
        "city-spot": {
            "id": 5,
            "name": "Downtown",
        }
    }
]

进入这个:

[{
        "id": 1,
        "name": Sally,
        "country": "Chile",
        "city": "Santiago",
        "city-spot": "Downtown",
    },

    {
        "id": 2,
        "name": Tom,
        "country": "Canada",
        "city": "Vancouver",
        "city-spot": "Downtown",
    }
]

2 个答案:

答案 0 :(得分:1)

Array#map数组中的每个对象,_.mapValues()为扁平形式:

var data = [{"id":1,"name":"Sally","country":{"id":1,"name":"Chile"},"city":{"id":1,"name":"Santiago"},"city-spot":{"id":1,"name":"Downtown"}},{"id":2,"name":"Tom","country":{"id":3,"name":"Canada"},"city":{"id":2,"name":"Vancouver"},"city-spot":{"id":5,"name":"Downtown"}}];

var result = data.map(function(o) {
  return _.mapValues(o, function(value) {
    return _.get(value, 'name', value); // if name found in value return name, if not return value
  });
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

答案 1 :(得分:0)

你不需要lodash,下划线。你可以使用Array#map。

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');

var index = require('./routes/index');
var app_index = require('./routes/app');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

app.use(session({ secret: 'ashasjasdiw', resave: true, saveUninitialized: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/app', app_index);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
app.listen(3000);
module.exports = app;