【问题标题】:Find out the particular object from array of objects [duplicate]从对象数组中找出特定对象[重复]
【发布时间】:2021-08-20 15:02:24
【问题描述】:

我有类似的数据

const data = {
  Name : "Apple",
  Weight : 5,
  Address : "Somewhere",
  Contact : 777666,
  X : 908,
  Y : 562,
}

另一个数据数组为

const arrData = ["Name","Weight"];

现在我需要一个变量中的对象的新数据,该变量的键等于数据数组。 例如所需的数据是

newData = [
  {Name : "Apple"},
  {Weight: "5"},
]

【问题讨论】:

  • 向我们展示您的尝试。 SO 不是免费的代码编写服务。此处的目的是让您发布解决自己问题的尝试,并在其他人无法按预期工作时提供帮助。见How to Askminimal reproducible example
  • 提示:您需要遍历arrData 并设置对象的每个属性。您可以使用reduce 或一个简单的循环。
  • console.log(["Name","Weight"].reduce((a,b)=>(data[b]&&(a[b]=data[b]),a),{}))

标签: javascript reactjs


【解决方案1】:

寻找这个?

const data = { Name : "Apple", Weight : 5, Address : "Somewhere", Contact : 777666, X : 908, Y : 562, }

const arrData = ["Name","Weight"];

// Define a new object that holds your result
const result = {};

// Loop trought every key using `.forEach` (can also be done using while/for loop)
// ... and writing a new property to result (using e as key and data[e] as value)
arrData.forEach(e => result[e] = data[e]);
console.log(result)

或者甚至是单线:

const data = {
  Name: "Apple",
  Weight: 5,
  Address: "Somewhere",
  Contact: 777666,
  X: 908,
  Y: 562,
}

const result = (o={},["Name", "Weight"].map((e, v)=>o[e]=data[e] ), o);
console.log(result)

【讨论】:

    【解决方案2】:

    const data = {
      Name: "Apple",
      Weight: 5,
      Address: "Somewhere",
      Contact: 777666,
      X: 908,
      Y: 562,
    }
    const arrData = ["Name", "Weight"];
    let newData = {};
    arrData.forEach(x => {
      newData[x] = data[x]
    })
    
    console.log(newData);

    【讨论】:

      猜你喜欢
      • 2019-12-03
      • 2018-08-23
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 2014-05-01
      • 2020-12-19
      相关资源
      最近更新 更多